/*
 * Created on Mar 23, 2006
 *
 */
package org.mushroomdb.triggers;

import org.mushroomdb.engine.EvaluationEngineFactory;
import org.mushroomdb.query.Query;
import org.mushroomdb.service.ServiceManager;
import org.mushroomdb.storedprocedures.StoredProcedure;
import org.mushroomdb.storedprocedures.StoredProceduresService;

/**
 * @author Matu
 */
public class Trigger {
	
	public final static int INSERT_OPERATION = 0;
	public final static int DLETE_OPERATION = 1;
	public final static int UPDATE_OPERATION = 2;
	
	public final static int BEFORE = 0;
	public final static int AFTER = 1;
	
	public final static int ROW_MODE = 0;
	public final static int STATEMENT_MODE = 1;
	
	private String name;
	private int operation;
	private int type;
	private int mode;
	private Object executable;
	
	/**
	 * 
	 * @param name
	 * @param operation
	 * @param type
	 * @param mode
	 * @param query
	 */
	public Trigger(String name, int operation, int type, int mode, Query query) {
		this.constructTrigger(name,operation,type,mode,query);
	}
	
	/**
	 * 
	 * @param name
	 * @param operation
	 * @param type
	 * @param mode
	 * @param storedProcedure
	 */
	public Trigger(String name, int operation, int type, int mode, StoredProcedure storedProcedure) {
		this.constructTrigger(name,operation,type,mode,storedProcedure);
	}
	
	/**
	 * 
	 * @param name
	 * @param operation
	 * @param type
	 * @param mode
	 * @param executable
	 */
	private void constructTrigger(String name, int operation, int type, int mode, Object executable) {
		this.name = name;
		this.operation = operation;
		this.type = type;
		this.mode = mode;
		this.executable = executable;
	}
	
	/**
	 * 
	 * @return
	 */
	public String getName() {
		return this.name;
	}
	
	/**
	 * 
	 * @return
	 */
	public int getOperation() {
		return this.operation;
	}
	
	/**
	 * 
	 * @return
	 */
	public int getType() {
		return this.type;
	}
	
	/**
	 * 
	 * @return
	 */
	public int getMode() {
		return this.mode;
	}
	
	/**
	 * Fires this trigger.
	 */
	public void fire() {
		if (executable instanceof Query) {
			((Query) executable).execute(EvaluationEngineFactory.getInstance());
		} else if (executable instanceof StoredProcedure) {
			StoredProceduresService storedProceduresService = (StoredProceduresService) ServiceManager.getInstance().getService(StoredProceduresService.class);
			storedProceduresService.execute(((StoredProcedure) executable));
		}
	}
}
